<template>
    <div class="dome">
        <div class="cropper">
            <img :src="cropImg || img" class="img" />
            <h5-cropper
              :option="option"
              @getbase64Data="getbase64Data"
              @getblobData="getblobData"
              @getFile="getFile"
            ></h5-cropper>
        </div>
    </div>
</template>

<script>
import "vue-cropper-h5/dist/style.css";
import H5Cropper  from 'vue-cropper-h5'
import CORSSDK from 'cos-js-sdk-v5'
import http from '../../http/index.js'

export default {
    components: { H5Cropper },
    props: [ 'cropImg' ],
    data () {
        return {
            option: {
                fixedBox: false
            }, //配置
            img: "//projectimg-1256680128.cos.ap-beijing.myqcloud.com/lpm/b9db4aaf-8c10-4b67-87f7-023944cab5ea.png",
            cors: {},
            corsConfig: {
                bucket: 'projectimg-1256680128', /* 填入您自己的存储桶，必须字段 */
                region: 'ap-beijing',  /* 存储桶所在地域，例如ap-beijing，必须字段 */
                key: 'lpm/', /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
            },
        }
    },
    mounted() {
        this.getCors()
    },
    methods: {
        upload(body) {
            var _this = this
            this.cors.putObject({
                Bucket: this.corsConfig.bucket, /* 填入您自己的存储桶，必须字段 */
                Region: this.corsConfig.region,  /* 存储桶所在地域，例如ap-beijing，必须字段 */
                Key: this.corsConfig.key + this.uuid() + '.png',  /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */
                Body: body,
                onProgress: function(progressData) {
                    console.log(progressData)
                    }
                }, (err, data) => {
                    if(err) {
                        fileRaw.status = 'failed';
                        fileRaw.message = '上传失败';
                        return false
                    }
                    // console.log(data)
                    _this.$emit("cropSucc", data.Location)
                    _this.getCors()
                })
                
        },
        getbase64Data(data) {
            this.upload(this.base2blob(data))
        },
        base2blob(dataurl) {
            var arr = dataurl.split(',');
            var mime = arr[0].match(/:(.*?);/)[1];
            var bstr = atob(arr[1]);
            var n = bstr.length;
            var u8arr = new Uint8Array(n);
            while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
            }
            return new Blob([u8arr], { type: mime });
        },
        getblobData() {

        },
        getFile() {

        },
        getCors() {
            this.cors = new CORSSDK({
                getAuthorization: this.getAuthorization
            })
        },
        getAuthorization (options, callback) {
            http.get('http://cnf2022adminserver.shanghaistroke-cnf.com/common/tencent/cors/authorization').then(res => {
                let credentials = res.data
                let result = {
                TmpSecretId: credentials.tmpSecretId,
                TmpSecretKey: credentials.tmpSecretKey,
                SecurityToken: credentials.sessionToken,
                // 建议返回服务器时间作为签名的开始时间，避免用户浏览器本地时间偏差过大导致签名错误
                StartTime: credentials.startTime, // 时间戳，单位秒，如：1580000000
                ExpiredTime: credentials.expiredTime, // 时间戳，单位秒，如：1580000000
                }
                this.corsConfig = {
                ...result,
                ...this.corsConfig
                }
                if(callback) {
                callback(result)
                }
            })
        },
        uuid () {
            var s = []
            var hexDigits = '0123456789abcdefghi'
            for (var i = 0; i < 36; i++) {
                s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
            }
            s[14] = '4' // bits 12-15 of the time_hi_and_version field to 0010
            s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1) // bits 6-7 of the clock_seq_hi_and_reserved to 01
            s[8] = s[13] = s[18] = s[23] = '-'

            var uuid = s.join('')
            return uuid
        }
    }
}
</script>
<style scoped>
.dome {
  display: flex;
  justify-content: space-between;
  padding-left: 22px;
}
.cropper {
  width: 80px;
  height: 80px;
  line-height: 80px;
  /* 切记position: relative一定要有 */
  position: relative;
  border-radius: 80px;
  overflow: hidden;
  text-align: center;
}
.img {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
}
.info {
  font-size: 18px;
  height: 40px;
  line-height: 40px;
  margin-left: 30px;
  flex: 1;
  text-align: left;
}
</style>